﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class PriorityQueue
    {
        readonly List<int> _list;

        public int Min { get { return _list[0]; } }

        public IEnumerable<int> Items { get { return _list; } }

        public PriorityQueue()
        {
            _list = new List<int>();
        }

        public void Insert(int v)
        {
            _list.Add(v);
            CreateHeap();
        }

        public int RemoveMin()
        {
            var min = Min;
            _list.RemoveAt(0);
            CreateHeap();
            return min;
        }

        private void CreateHeap()
        {
            for (int i = _list.Count / 2; i > -1; i--)
            {
                Heapify(i);
            }
        }

        private void Heapify(int i)
        {
            var leftIndex = i * 2;
            var rightIndex = leftIndex + 1;

            var leftValue = int.MaxValue;
            var rightValue = int.MaxValue;

            if (leftIndex < _list.Count)
            {
                leftValue = _list[leftIndex];
            }
            if (rightIndex < _list.Count)
            {
                rightValue = _list[rightIndex];
            }

            if (leftValue < rightValue)
            {
                if (leftValue < _list[i])
                {
                    Swap(i, leftIndex);
                    Heapify(leftIndex);
                }
            }
            else if (rightValue < leftValue)
            {
                if (rightValue < _list[i])
                {
                    Swap(i, rightIndex);
                    Heapify(rightIndex);
                }
            }
        }

        private void Swap(int i, int j)
        {
            var temp = _list[j];
            _list[j] = _list[i];
            _list[i] = temp;
        }
    }
}